package com.sjgtw.cloud.web.path.service.impl;

import com.sjgtw.cloud.common.core.constant.CacheConstants;
import com.sjgtw.cloud.common.core.utils.DateUtils;
import com.sjgtw.cloud.common.core.utils.SecurityUtils;
import com.sjgtw.cloud.common.core.utils.bean.BeanUtils;
import com.sjgtw.cloud.common.redis.service.RedisService;
import com.sjgtw.cloud.system.api.model.LoginUser;
import com.sjgtw.cloud.web.path.domain.EmergencyPath;
import com.sjgtw.cloud.web.path.domain.PathPoint;
import com.sjgtw.cloud.web.path.domain.UpperLocation;
import com.sjgtw.cloud.web.path.dto.UpperLocationDTO;
import com.sjgtw.cloud.web.path.mapper.EmergencyPathMapper;
import com.sjgtw.cloud.web.path.mapper.PathPointMapper;
import com.sjgtw.cloud.web.path.mapper.UpperLocationMapper;
import com.sjgtw.cloud.web.path.service.IUpperLocationService;
import com.sjgtw.cloud.web.path.vo.EmergencyPathVO;
import com.sjgtw.cloud.web.path.vo.UpperLocationVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 上道地点Service业务层处理
 *
 * @author lvyoufang
 * @date 2024-03-19
 */
@Service
public class UpperLocationServiceImpl implements IUpperLocationService
{
    @Autowired
    private UpperLocationMapper upperLocationMapper;
    @Autowired
    private EmergencyPathMapper emergencyPathMapper;
    @Autowired
    private PathPointMapper pathPointMapper;

    @Autowired
    private RedisService redisService;

    /**
     * 查询上道地点
     *
     * @param id 上道地点主键
     * @return 上道地点
     */
    @Override
    public UpperLocationVO selectUpperLocationById(Long id)
    {
        UpperLocationVO locationVO = new UpperLocationVO();
        UpperLocation upperLocation = upperLocationMapper.selectUpperLocationById(id);
        BeanUtils.copyProperties(upperLocation, locationVO);

        EmergencyPath emergencyPath = new EmergencyPath();
        emergencyPath.setUpperId(id);
        List<EmergencyPath> paths = emergencyPathMapper.selectEmergencyPathList(emergencyPath);

        PathPoint pathPoint = new PathPoint();
        pathPoint.setUpperId(id);
        List<PathPoint> pathPoints = pathPointMapper.selectPathPointList(pathPoint);
        Map<Long, List<PathPoint>> pointMap = pathPoints.stream().collect(Collectors.groupingBy(PathPoint::getPathId));

        List<EmergencyPathVO> pathVOS = new ArrayList<>();
        if (paths.size() > 0) {
            for (EmergencyPath path : paths) {
                EmergencyPathVO pathVO = new EmergencyPathVO();
                BeanUtils.copyProperties(path, pathVO);

                List<PathPoint> points = pointMap.get(path.getId());
                pathVO.setPoints(points);
                pathVOS.add(pathVO);

                List<List<BigDecimal>> locations = new ArrayList<>();
                List<Map> locationMap = new ArrayList<>();
                if (points != null) {
                    for (PathPoint point : points) {
                        List<BigDecimal> location = new ArrayList<>();
                        location.add(point.getLongitude());
                        location.add(point.getLatitude());
                        locations.add(location);

                        Map map = new HashMap();
                        map.put("lat", point.getLatitude());
                        map.put("lon", point.getLongitude());
                        locationMap.add(map);
                    }
                }
                pathVO.setLocations(locations);
                pathVO.setLocationMap(locationMap);
            }
        }
        locationVO.setPaths(pathVOS);
        return locationVO;
    }

    /**
     * 查询上道地点列表
     *
     * @param upperLocation 上道地点
     * @return 上道地点
     */
    @Override
    public List<UpperLocation> selectUpperLocationList(UpperLocationDTO upperLocation)
    {
        return upperLocationMapper.selectUpperLocationList(upperLocation);
    }

    /**
     * 新增上道地点
     *
     * @param upperLocation 上道地点
     * @return 结果
     */
    @Override
    public int insertUpperLocation(UpperLocation upperLocation)
    {
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

        upperLocation.setCreateUserId(user.getUserid());
        upperLocation.setCreateBy(user.getUsername());
        upperLocation.setCreateTime(DateUtils.getNowDate());
        return upperLocationMapper.insertUpperLocation(upperLocation);
    }

    /**
     * 修改上道地点
     *
     * @param upperLocationVO 上道地点
     * @return 结果
     */
    @Override
    public int updateUpperLocation(UpperLocationVO upperLocationVO)
    {
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

        UpperLocation upperLocation = new UpperLocation();
        BeanUtils.copyProperties(upperLocationVO, upperLocation);
        upperLocation.setUpdateBy(user.getUsername());
        upperLocation.setUpdateTime(DateUtils.getNowDate());

        emergencyPathMapper.deleteNotExist(upperLocation.getId(), null);
        pathPointMapper.deleteNotExist(upperLocation.getId(), null);

        List<EmergencyPathVO> pathVOS = upperLocationVO.getPaths();
        emergencyPathMapper.deleteNotExist(upperLocation.getId(), null);
        pathPointMapper.deleteNotExist(upperLocation.getId(), null);

        for (EmergencyPathVO pathVO : pathVOS) {
            EmergencyPath path = new EmergencyPath();
            BeanUtils.copyProperties(pathVO, path);
            path.setUpperId(upperLocationVO.getId());
            path.setCreateUserId(user.getUserid());
            path.setCreateBy(user.getUsername());
            path.setCreateTime(DateUtils.getNowDate());
            emergencyPathMapper.insertEmergencyPath(path);

            List<PathPoint> points = pathVO.getPoints();
            if (points != null) {
                for (PathPoint point : points) {
                    point.setUpperId(upperLocationVO.getId());
                    point.setPathId(path.getId());
                    point.setCreateBy(user.getUsername());
                    point.setCreateTime(DateUtils.getNowDate());
                    pathPointMapper.insertPathPoint(point);
                }
            }
        }

        return upperLocationMapper.updateUpperLocation(upperLocation);
    }

    /**
     * 批量删除上道地点
     *
     * @param ids 需要删除的上道地点主键
     * @return 结果
     */
    @Override
    public int deleteUpperLocationByIds(String[] ids)
    {
        return upperLocationMapper.deleteUpperLocationByIds(ids);
    }

    /**
     * 删除上道地点信息
     *
     * @param id 上道地点主键
     * @return 结果
     */
    @Override
    public int deleteUpperLocationById(Long id)
    {
        pathPointMapper.deleteNotExist(id, null);
        emergencyPathMapper.deleteNotExist(id, null);
        return upperLocationMapper.deleteUpperLocationById(id);
    }
}
